package com.xxz.controller;
import com.xxz.dao.DepartmentDao;
import com.xxz.dao.EmployeeDao;
import com.xxz.pojo.Department;
import com.xxz.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Collection;
@Controller
public class EmployeeController {
    @Autowired
    EmployeeDao employeeDao;
    //  1   显示页面
    @RequestMapping("/emps")   //url 请求路径 这是 显示 列表请求
    public String list(Model model){
         Collection<Employee> employees = employeeDao.getEmployeeAll();
         model.addAttribute("emps",employees);
         return  "emp/list";   //  响应路径
    }

    @Autowired
    DepartmentDao departmentDao;
    // 2   去到添加页面
    @GetMapping ("/toadd") //和 list.html那的请求路径保持一致
    public String toAddpage(Model model){  //去到添加页面
        //查出所有部门的信息。
        Collection<Department> departments = departmentDao.departments(); //这里的方法对应的是departmentDao中获得部门信息的方法
        model.addAttribute("departments",departments);
        return "emp/add";  // 响应目录
    }

    //   3   添加员工的操作
    @PostMapping("/toadd")
    public String addEmp(Employee employee){
        System.out.println("addEmployee=>"+employee);
        employeeDao.addEmployee(employee); //执行完这个代码  数据就保存更新了 调用地底层业务方法。保存员工信息
        return "redirect:/emps";
    }


    //    4      到员工的修改页面。
    @RequestMapping("/emp/{id}")   // restful风格接收参数
    public String toUpdateEmp(@PathVariable("id")Integer id, Model model){
        //查出原来的数据
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp",employee);
       //查出所有的部门信息,添加到departments中,用于前端接收
       Collection<Department>  departments = departmentDao.departments();
       model.addAttribute("departments",departments);
        return "emp/update";
    }

    //   5    修改员工的操作
    @PostMapping("/emp")
    public String updateEmp(Employee employee){
        System.out.println("addEmployee=>"+employee);
        employeeDao.addEmployee(employee);  // 这的方法是增加方法
        return "redirect:/emps";    //   修改完返回 展示页面
    }


    //    6   删除员工
    @GetMapping("/delemp/{id}")// restful风格接收参数  一定是通过id来传递的
    public String deleteEmp(@PathVariable("id") int id){
        employeeDao.deleteEmployee(id);
        return "redirect:/emps";
    }
}
